<?php

namespace app\admin\controller\health\website;

use app\common\controller\Backend;
use app\health\model\HealthWebsiteTask;
use app\health\model\HealthWebsiteVideo;
use Exception;
use PDOException;
use think\Db;

class Task extends Backend
{
    /**
     * @var null|HealthWebsiteTask $model
     */
    protected $model = null;

    /**
     * @return void
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model  = new HealthWebsiteTask();
        $category_map = [];
        foreach (HealthWebsiteTask::CATEGORY_MAP as $k => $v) {
            $category_map[] = ['name' => $k, 'label' => $v];
        }
        $award_type_map = [];
        foreach (HealthWebsiteTask::AWARD_TYPE_MAP as $k => $v) {
            $award_type_map[] = ['name' => $k, 'label' => $v];
        }
        $complete_way_map = HealthWebsiteTask::completeWayRule();
        $this->assignconfig('category_map', $category_map);
        $this->assignconfig('award_type_map', $award_type_map);
        $this->assignconfig('complete_way_map', $complete_way_map);
    }

    /**
     * 任务列表
     * @return string|\think\response\Json|null
     * @throws \think\Exception
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $nobuildfields = [];
            [$where, $sort, $order, $offset, $limit] = $this->custombuildparams(null, $nobuildfields);
            $total = $this->buildSearch()
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list  = $this->buildSearch()
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $item) {
                $item->append(['award_type_text', 'complete_way_text', 'status_text']);
            }
            $result = ["total" => $total, "rows" => $list];
            $this->success('操作成功', null, $result);
        }
        $this->assign('title', '网赚任务管理');
        return $this->view->fetch();
    }

    /**
     * @return HealthWebsiteTask
     */
    protected function buildSearch(): HealthWebsiteTask
    {
        $model = $this->model;
        if ($this->request->has('category')) {
            $model = $model->where('category', $this->request->param('category'));
        }
        return $this->model;
    }

    /**
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params = json_decode($params['data'], true);
            $result = $this->validate($params, [
                'name|任务名称'         => 'require',
                'description|任务描述'  => 'require',
                'complete_num|完成次数' => 'require|number|min:1',
                'award_type|奖励类型'   => 'require|in:1,2',
                'award_value|奖励值'    => 'require',
                'complete_way|完成方式' => 'require',
            ]);
            if (true !== $result) {
                $this->error($result);
            }
            $completeWayContent = $params['complete_way_content'] ?? [];
            unset($params['complete_way_content']);
            $params['complete_way_content'] = [];
            if ($params['complete_way'] == 1) {
                if (empty($completeWayContent['video_id']) || empty($completeWayContent['duration'])) {
                    $this->error('请设置完整的视频观看内容');
                }
                $params['complete_way_content'] = ['video_id' => $completeWayContent['video_id'], 'duration' => $completeWayContent['duration']];
            }
            $this->model->create($params);
            $this->success("添加成功");
        }
        $this->assignconfig('category', $this->request->param('category', 1));
        $this->assign('title', '创建网赚任务');
        return $this->view->fetch();
    }

    /**
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $params = json_decode($params['data'], true);
            $result = $this->validate($params, [
                'name|任务名称'         => 'require',
                'description|任务描述'  => 'require',
                'complete_num|完成次数' => 'require|number|min:1',
                'award_type|奖励类型'   => 'require|in:1,2',
                'award_value|奖励值'    => 'require',
                'complete_way|完成方式' => 'require',
            ]);
            if (true !== $result) {
                $this->error($result);
            }
            if (!$row) {
                $this->error('任务不存在');
            }
            $completeWayContent = $params['complete_way_content'] ?? [];
            unset($params['complete_way_content']);
            $params['complete_way_content'] = [];
            if ($params['complete_way'] === 1) {
                if (empty($completeWayContent['video_id']) || empty($completeWayContent['duration'])) {
                    $this->error('请设置完整的视频观看内容');
                }
                $params['complete_way_content'] = ['video_id' => $completeWayContent['video_id'], 'duration' => $completeWayContent['duration']];
            }
            $row->save($params);
            $this->success("修改成功");
        }
        $this->assignconfig("row", $row);
        $this->assign('title', '编辑网赚任务');
        return $this->view->fetch();
    }

    /**
     * 设置任务状态
     * @param [type] $ids
     * @param [type] $status
     * @Author 张旭鹏
     * @DateTime 2023-07-13
     */
    public function setStatus($ids, $status): void
    {
        if ($ids) {
            $pk    = $this->model->getPk();
            $list  = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $v->status = $status;
                    $count     += $v->save();
                }
                Db::commit();
            } catch (PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function video_lists()
    {
        $lists = HealthWebsiteVideo::all();
        $this->success('视频列表', '', $lists);
    }
}
